﻿<?php 
class Pay extends CI_Controller{
    var $alipay_params = "";
    function __construct(){
        parent::__construct();
        $this->load->helper('url');
        $this->sen_data = $this->session->userdata('wb_userinfo');
        $this->load->model('Mwbuser');
        $this->alipay_params = $this->config->item('alipay');
        $this->load->helper('alipayfuns');
    }
    
    function getprice()
    {
        $arr = array (
            "status"=>0,
            "info"=> "",
            "data"=>""
            );
        $this->db->order_by('p_price','asc');
        $this->db->from('wtt_products');
        $query = $this->db->get();
        if($query->num_rows() > 0 )
        {
            $arr['status'] = 1;
            $checked = 'checked="true" ';
            $style = '';
             foreach($query->result_array() as $row)
            {
              if($style == ''){
                $arr['data'] .= '<label style="line-height:14px;"><br><input value="'.$row['p_price'].'" type="radio" '.$checked.' name="price" class="left radiofix"/>';
               
                $style ='ok';
              }else{
                $arr['data'] .= '<label style="line-height:14px;"><br><input value="'.$row['p_price'].'" type="radio" '.$checked.' name="price" class="left radiofix"/>';
               //class="left" style="margin-left:40px;_margin-left:50px;" 两行
                $style ='';
              }
              $arr['data'] .= '<span class="left">'.$row['p_name'].'</span></label>';
              $checked = '';
            }
        }
         header("content-type: text/html; charset=utf-8");
         echo json_encode($arr);
    }
    /*
     * 支付页面
     */    
    function alipayto(){
        $this->chklogin();
        $price = $this->input->post('price');
        if(is_numeric($price) == false)
        {
            show_error('参数格式错误', '200', '参数错误');
        }
        $query = $this->db->get_where("wtt_products",array("p_price"=>$price));
        if($query->num_rows() < 0)
        {
            show_error("您所选择的产品不存在！",200,"参数错误");
        }else{
            $row = $query->row_array(); 
            $order_id = date('YmdHis');
            $order_subject = '充值'.$row['p_name'];
         //写入订单
            $DB1 = $this->load->database('update', TRUE);
         $data = array(
               'order_id' => $order_id ,
               'pro_id' => $price ,
               'wb_id' => $this->sen_data['wb_id'],
               'create_time' => time(),
               'order_status'=>0
            );

        $DB1->insert('wtt_payorder', $data); 
           
        $alipay_params = $this->alipay_params;
        //订单号码
        $data['order']['number']=date('Ymdhis');
        //订单中金额
        //$data['order']['total_fe'] = $price;
        //订单主题
        $data['order']['subject'] = $order_subject;
        //订单备注信息
        //$data['order']['body'] = $order_subject;
        //显示订单详细信息页面
        //$data['alipay']['show_url'] = base_url().'index.php/';
        $alipay_params['show_url'] = '';
        
        //构造要请求的参数数组
        $parameter = array(
		"service"			=> "create_direct_pay_by_user",
		"payment_type"		=> "1",
		
		"partner"			=> trim($alipay_params['partner']),
		"_input_charset"	=> trim(strtolower($alipay_params['input_charset'])),
        "seller_email"		=> trim($alipay_params['seller_email']),
        "return_url"		=> trim($alipay_params['return_url']),
        "notify_url"		=> trim($alipay_params['notify_url']),

        "out_trade_no"		=> $data['order']['number'],
        "subject"			=> $data['order']['subject'],        
        "price"				=>$price,
		"quantity"			=> 1,
		
		"logistics_fee"		=> $price,
		"logistics_type"	=> 'EXPRESS',
		"logistics_payment"	=> 'SELLER_PAY',
		
		"receive_name"		=> '',
		"receive_address"	=> '',
		"receive_zip"		=> '',
		"receive_phone"		=> '',
		"receive_mobile"	=> '',
		
        	"show_url"			=> ''
);
		//$data['server_url'] = $alipay_params['server_url'];
        $alipayService = new AlipayService($alipay_params);
        $data['para'] = $alipayService->create_partner_trade_by_buyer($parameter);
        header("content-type: text/html; charset=utf-8");
        echo $data['para'];
        }
        
        
     
        
        
        
        //$this->load->view('include/header');
        //$this->load->view('payorder',$data);
        //$this->load->view('include/footer');        
    }
	function return1_url(){
		 $out_trade_no	= $_GET['out_trade_no'];	//获取订单号
		if($this->input->get('trade_status') == 'TRADE_SUCCESS'){
		    $db1 = $this->load->database('update', TRUE);
		    $db1->query("update wtt_addres set paystatus='支付宝已支付'   where order_id=". $out_trade_no);
					
                    echo "<a href=\"javascript:window.opener='anyone';windows.close();\">支付成功点击关闭页面</a>";
		}
	}
    /*
     * 支付宝同步回调通知接口
     */
    function return_url(){
        //$this->config->set_item('global_xss_filtering', false);
      //  $inputs = $this->input->post();
      
        //验证是不是支付宝的数据
        //if($this->_verify($inputs)){
            //TODO：查看消息是否已经处理，未处理则更新订单数据库
            $out_trade_no	= $_GET['out_trade_no'];	//获取订单号
            $trade_no		= $_GET['trade_no'];		//获取支付宝交易号
            $total_fee		= $_GET['total_fee'];			//获取总价格
           if($this->input->get('trade_status') == 'TRADE_SUCCESS'){
                
                $this->db->select("a.wb_id,a.pro_id,a.order_status,b.screen_name");
                $this->db->from('wtt_payorder a');
                $this->db->join('wtt_customers b','a.wb_id=b.wb_id','INNER');
                $this->db->where('a.order_id',$out_trade_no);
                $query = $this->db->get_where("wtt_payorder",array("a.order_id"=>$out_trade_no));
               // $query = $this->db->get();
                if($query->num_rows() > 0)
                {
                    $row = $query->row_array();
                    if($row['order_status'] == '0')
                    {
                        $wb_id = $row['wb_id'];
                        $pro_id = $row['pro_id'];
                        $screen_name = $row['screen_name'];
                        $query = $this->db->get_where("wtt_products",array("p_price"=>$pro_id));
                        if($query->num_rows() < 0)
                        {
                            show_error("您所选择的产品不存在！",200,"参数错误");
                        }else{
                           $DB1 = $this->load->database('update', TRUE);
                            $row = $query->row_array(); 
                            $jifen = $row['p_jifen'];
                            
                            //$this->db->query("updatge wtt_customers set jifen=jifen+".$jifen." where wb_id=".$pro_id);
                            
                            $muid = $this->Mwbuser->getinfo($wb_id,'jifen');
                            $nejifen = $muid['jifen']  < 0 ? abs($muid['jifen']) : 0;
                            $this->Mwbuser->setpoints($wb_id,($jifen+$nejifen),1);
                            $this->Mwbuser->insertlog($wb_id,0,$screen_name,3,$jifen,0,1);
                            $DB1->query("update wtt_payorder set order_status=1 where order_id='".$out_trade_no."'");
                            header("content-type: text/html; charset=utf-8");
							header('Location:/welcome');
			 
                        }
                        
                    }else{
                        show_error("订单已经处理，不可多次处理","200","订单错误！");
                    }
                    
                }else{
                    show_error("订单不存在","200","订单错误！");
                }
            
           }else
           {
                header("content-type: text/html; charset=utf-8");
                echo "非法参数";
                
           }
           
            //提示用户支付成功
            //$view = 'success';
        //}else{
            //不是支付宝的消息
           // header("content-type: text/html; charset=utf-8");
           // echo "非法参数1";
        //}        
       // $this->load->view('include/header');
       // $this->load->view($view,$data);
       // $this->load->view('include/footer');  
    }
    /*
     * 支付宝异步通知接口
     */
    function notify(){
        $inputs = $this->input->post();
        //查看消息是否已经处理
        //验证是不是支付宝的数据
        
        //更新自己数据库
        
        //记录日志
        echo "success";
        exit();          
    }
    /*
     * 验证消息来源
     */
    function _verify($inputs) {
        $alipay_params = $this->alipay_params;
        $alipayNotify = new AlipayNotify($alipay_params);
        return $alipayNotify->verifyNotify($inputs);

    }
     private function chklogin(){
        if(!$this->session->userdata('wb_userinfo')){
            redirect('/welcome');
        }
    }

 /*
     * 支付页面
     */    
    function makaalipayto(){
     //   $this->chklogin();
   
        $product = $this->input->post('product');
  		$price = $this->input->post('prize');
       		$pay = $this->input->post('pay');
          $num = $this->input->post('mun');
          $lianxiren = $this->input->post('name');
          $phone = $this->input->post('mob');
          $tel = $this->input->post('tel');
          $addressinfo = $this->input->post('province3').$this->input->post('city3').$this->input->post('area3').$this->input->post('address');
          $youbian = $this->input->post('youbian');
            $paytype = $this->input->post('paytype');
             $liuyan = $this->input->post('liuyan');
		$userid= $this->input->post('userid');

       	if($product == '摩力挺玛卡喷剂 [激情强效装] 390元|390')
      	{ 
      		$productname = "摩力挺玛卡喷剂 [激情强效装] 390元";
      		$total_fee = 390;
      	}else{ 
      		$productname = "摩力挺玛卡喷剂 [激情体验装] 290元";
      		$total_fee = 290;
      	}
 		$order_id = date('Ymdhis');
              //写入订单
	
	
            $DB1 = $this->load->database('update', TRUE);
         $data = array(
                'order_id' => $order_id ,
               'tel' => $tel ,
               'phone' => $phone,
               'productname' =>$productname,
               'lianxiren' => $lianxiren,
               'num'=>$num,
               'paytype'=>$paytype,
               'liuyan'=>$liuyan,
               'total_fee'=>$price  ,
               'addressinfo'=>$addressinfo,
               'youbian'=>$youbian,
               'paytype'=>$pay,
	       'userid'=>$userid ,
	       'add_time'=>time(),
		
               'status'=>0
             
            );

        $DB1->insert('wtt_addres', $data); 
	if($pay ==1 || $pay == 3)
	{
		if($pay == 3)
		{
			$paystatus = "银行卡支付";
		}else{
 			$paystatus = "货到付款";
		}
		 $db1 = $this->load->database('update', TRUE);
		 $db1->query("update wtt_addres set paystatus='".$paystatus."'   where order_id=".$order_id);
		echo "<script> alert('下单成功');parent.location.href='/welcome';</script>";
	}
	
      else if($pay ==2){
          
           
            $order_subject =$productname;
        
         
        $alipay_params = $this->alipay_params;
        //订单号码
        $data['order']['number']=date('Ymdhis');
        //订单中金额
        //$data['order']['total_fe'] = $price;
        //订单主题
        $data['order']['subject'] = $order_subject;
        //订单备注信息
        //$data['order']['body'] = $order_subject;
        //显示订单详细信息页面
        //$data['alipay']['show_url'] = base_url().'index.php/';
        $alipay_params['show_url'] = '';
        
        //构造要请求的参数数组
        $parameter = array(
		"service"			=> "create_direct_pay_by_user",
		"payment_type"		=> "1",
		
		"partner"			=> trim($alipay_params['partner']),
		"_input_charset"	=> trim(strtolower($alipay_params['input_charset'])),
        "seller_email"		=> trim($alipay_params['seller_email']),
        "return_url"		=>  'http://www.aihufen.com/pay/return1_url',
        "notify_url"		=> trim($alipay_params['notify_url']),

        "out_trade_no"		=> $data['order']['number'],
        "subject"			=> $data['order']['subject'],        
        "price"				=>	 0.01,
		"quantity"			=> 1,
		
		"logistics_fee"		=> '0.00',
		"logistics_type"	=> 'EXPRESS',
		"logistics_payment"	=> 'SELLER_PAY',
		
		"receive_name"		=> '',
		"receive_address"	=> '',
		"receive_zip"		=> '',
		"receive_phone"		=> '',
		"receive_mobile"	=> '',
		
        "show_url"			=> ''
);
		//$data['server_url'] = $alipay_params['server_url'];
        $alipayService = new AlipayService($alipay_params);
        $data['para'] = $alipayService->create_partner_trade_by_buyer($parameter);
        header("content-type: text/html; charset=utf-8");
        echo $data['para'];
        }

	}


}